import os
import datetime
import base64
from applications.extensions.init_upload import photos
from flask import current_app
from applications.models import Photo
from flask_login import login_required, current_user
from flask import Blueprint, render_template, request, jsonify
from applications.common.utils.rights import authorize
from applications.common.utils.http import fail_api
from applications.Deeplearning import img_predict
from applications.models import WikiDict, Wiki, History
from applications.common.utils import upload as upload_curd
from applications.extensions import db

pest_check = Blueprint('PestCheck', __name__, url_prefix='/')


def image_to_base64(path):
    with open(path, 'rb') as img:
        # 使用base64进行编码
        b64encode = base64.b64encode(img.read())
        s = b64encode.decode()
        b64_encode = 'data:image/jpeg;base64,%s' % s
        # 返回base64编码字符串
        return b64_encode


# 病害图片识别的视图
@pest_check.get('/pest_check')
# @authorize("pest:checkview", log=True)
def main():
    return render_template('admin/pest/check.html')


@pest_check.post('/pest_check/img')
# @authorize("pest:check", log=True)
def check_api():
    print('深度学习识别中...')
    if 'file' in request.files:
        f = request.files['file']

        path_now = os.path.dirname(os.path.realpath(__file__))
        path_up1 = os.path.dirname(path_now)
        path_up2 = os.path.dirname(path_up1)
        ori_path = os.path.dirname(path_up2)
        img_path = ori_path + '/static/image.jpg'
        f.save(img_path)

        print("深度学习模块...")
        ImgIdentResult, PredictAccuracy = img_predict(img_path)
        # 查询病害名
        wiki_name = WikiDict.query.filter(WikiDict.disease_name.like("%" + ImgIdentResult + "%")).all()
        ImgIdentResult = wiki_name[0].wiki_dname
        # 查询wiki数据，获取症状和防治信息
        wiki_info = Wiki.query.filter(Wiki.disease_name.like("%" + ImgIdentResult + "%")).all()
        disease_symptom = wiki_info[0].disease_symptom
        disease_prevention = wiki_info[0].disease_prevention

        # 转换base64
        img_url = image_to_base64(img_path)
        print("图片转换后", img_url)

        # 添加查询记录
        disease_name = wiki_info[0].disease_name
        search_time = datetime.datetime.now()
        user_id = current_user.realname

        search_ccuracy = PredictAccuracy
        search_img = img_url
        history_info = History(disease_name, search_time, user_id, search_ccuracy, search_img)
        db.session.add(history_info)
        db.session.commit()


        print("存放深度学习图片目录", img_path)
        print("识别结果:", ImgIdentResult)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {
                    "src": "http://127.0.0.1:5000/static/image.jpg",
                    'result': ImgIdentResult,
                    'accuracy': PredictAccuracy,
                    'symptom': disease_symptom,
                    'prevention': disease_prevention
                }
        }
        return jsonify(res)
    return fail_api()

